package com.dldata.devtools30.controller.sysform;

import com.alibaba.fastjson.JSON;

import com.dldata.devtools30.common.EnumUtils;
import com.dldata.devtools30.controller.DevBase30Controller;
import com.dldata.devtools30.entity.*;
import com.dldata.devtools30.repository.metadata.DevtModelMetadataFieldDao;
import com.dldata.devtools30.repository.metadata.DevtModelMetadataTableDao;
import com.dldata.devtools30.repository.sysform.DevtFormListtemplConfigDao;
import com.dldata.devtools30.repository.sysform.DevtFormMetadataDao;
import com.dldata.devtools30.service.sysform.DevtFormListTemplateService;
import com.dldata.devtools30.service.sysform.DevtFormTypeService;
import com.dldata.devtools30.utils.DateUtil;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import com.dldata.devtools30.utils.dataexport.DataExportUtil;
import com.dldata.devtools30.utils.dataexport.TableConfig;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.*;

/**

 */
@Controller
@RequestMapping(value = "/DevtFormListTemplateController")
public class DevtFormListTemplateController extends DevBase30Controller {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DevtFormListTemplateService sysCrfFormListTemplateService;

    @Autowired
    private DevtFormListtemplConfigDao sysCrfFormListtemplConfigDao;
    @Autowired
    private DevtFormTypeService formTypeService;
    
    @Autowired
    DevtFormMetadataDao sysCrfFormMetadataDao;
    @Autowired
    DevtModelMetadataTableDao sysModelMetadataTableDao;
    @Autowired
    DevtModelMetadataFieldDao sysModelMetadataFieldDao;
    
    @RequestMapping(value = "/getModelSql")
    @ResponseBody
    public Result getModelSql(@RequestParam Map<String, String> paramMap, HttpServletResponse response) throws Exception {
        List<DevtFormMetadataEntity> metadataEntityList = sysCrfFormMetadataDao.getDataByTempleid(paramMap.get("id"));
        if(metadataEntityList.size()==0){
            return Result.error("未绑定模型");
        }
        DevtModelMetadataTableEntity modelMetadataTableEntity= sysModelMetadataTableDao.findById(metadataEntityList.get(0).getTableid()).orElse(null);
        List<DevtModelMetadataFieldEntity> fieldEntityList = sysModelMetadataFieldDao.getAllByTid(metadataEntityList.get(0).getTableid());
        StringBuilder stringBuilder=new StringBuilder(" select ");
        for (int i = 0; i < fieldEntityList.size(); i++) {
            DevtModelMetadataFieldEntity sysModelMetadataFieldEntity = fieldEntityList.get(i);
            stringBuilder.append(sysModelMetadataFieldEntity.getFieldCode()).append(" , ");
        }
        if(stringBuilder.length()>10){
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
        }
        stringBuilder.append("\r\n");
        if(modelMetadataTableEntity.getStoretype().equalsIgnoreCase(EnumUtils.StoreTypeEnum.json.name())){
            stringBuilder.append(" from ");
            stringBuilder.append(" v_"+modelMetadataTableEntity.getCode());
        }else{
            stringBuilder.append(" from ");
            stringBuilder.append(modelMetadataTableEntity.getCode());
        }
        return Result.ok("查询成功",stringBuilder.toString());
    }

    @RequestMapping(value = "/getdata")
    @ResponseBody
    public Result getData(String id, String search) {

        if(StringUtil.isEmptyOrLength0(id)){
            return Result.error("参数有误");
        }
       DevtFormListtemplateEntity entity= sysCrfFormListTemplateService.getTemplateById(id);

        return Result.ok(entity) ;

    }
    @RequestMapping(value = "/saveSql")
    @ResponseBody
    public Result saveSql(String sql,String id, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {

        if(StringUtil.isEmptyOrLength0(sql) ){
            return Result.error("Sql不能为空");
        }
        if(StringUtil.isEmptyOrLength0(id) ){
            return Result.error("参数有误");
        }
        try {

            DevtFormListtemplateEntity entity=sysCrfFormListTemplateService.getTemplateById(id);
            if(entity==null){
                return Result.error("数据不存在");
            }
            entity.setTemlplesql(sql);

            sysCrfFormListTemplateService.save(entity);



            return Result.ok();
        }catch (Exception ex){

            logger.error("【执行"+this.getClass().getName()+".saveSql() 方法失败 】异常："+ex.getMessage());
            return Result.error("系统错误，请稍候再试");
        }

    }
    @RequestMapping(value = "/getDataByfl")
    @ResponseBody
    public Result getDataByFl(String flid,String search,String formid) {

        List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
        if(StringUtil.isEmptyOrLength0(search)){
            search="";
        }

        List<DevtFormListtemplateEntity>  tempfieldlist =new ArrayList<>();
        if(!StringUtil.isEmptyOrLength0(formid)){
            DevtFormListtemplateEntity listtemplate = sysCrfFormListTemplateService.getTemplateById(formid);
            if(listtemplate!=null){
                tempfieldlist.add(listtemplate);
            }
        }else{
            flid=(flid==null||flid.equals(""))?"":flid;
            flid="%"+flid+"%";
            search=(search==null||search.equals(""))?"":search;
            search="%"+search+"%";
            tempfieldlist=sysCrfFormListTemplateService.getDataByFl(flid,search);
        }
        
        List<DevtFormMetadataEntity> metadataAll = sysCrfFormMetadataDao.getAll();
     
        List<DevtFormTypeEntity> sysCrfFormTypeEntities= formTypeService.getAllFormType();
        tempfieldlist.stream().filter(
                sysCrfFormListtemplateEntity -> {

                    return (sysCrfFormListtemplateEntity.getStatus()==1);
                }
        ).forEach(
                (sysCrfFormTemplateEntity) -> {
                    Map<String, Object> tmpmap = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(sysCrfFormTemplateEntity));
                    tmpmap.put("id",sysCrfFormTemplateEntity.getId());
                    tmpmap.put("name",sysCrfFormTemplateEntity.getName());
                    tmpmap.put("bz",sysCrfFormTemplateEntity.getBz());
                    tmpmap.put("active",sysCrfFormTemplateEntity.getActive()!=null&&sysCrfFormTemplateEntity.getActive()==1?"是":"否");
                    tmpmap.put("standard",sysCrfFormTemplateEntity.getStandard()!=null&&sysCrfFormTemplateEntity.getStandard()==1?"是":"否");
                    tmpmap.put("status",sysCrfFormTemplateEntity.getStatus()!=null&&sysCrfFormTemplateEntity.getStatus()==0?"是":"否");
                    tmpmap.put("style","风格"+sysCrfFormTemplateEntity.getStytle());
                    String pageflag="不分页";
                    pageflag=sysCrfFormTemplateEntity.getPageflag()==2?"前台分页":pageflag;
                    pageflag=sysCrfFormTemplateEntity.getPageflag()==3?"后台分页":pageflag;
                    tmpmap.put("pageflag",pageflag);
                    tmpmap.put("createTime", DateUtil.formatFromDate(DateUtil.FORMATER_YYYY_MM_DD_HH_MM_SS, sysCrfFormTemplateEntity.getCreateTime()));
                    tmpmap.put("flmc","");
                    sysCrfFormTypeEntities.stream().filter(w->w.getId().equals(sysCrfFormTemplateEntity.getFlid())).forEach(m->{
                        tmpmap.put("flmc",m.getName());
                    });
    
                    tmpmap.put("metatableshow","");
                    DevtFormMetadataEntity formMetadataEntity = metadataAll.stream().filter(
                            sysFormMetadataEntity -> {
                                return sysFormMetadataEntity.getTempleid().equals(sysCrfFormTemplateEntity.getId());
                            }
                    ).findFirst().orElse(null);
                    if(formMetadataEntity!=null){
                        DevtModelMetadataTableEntity metadataTableEntity = sysModelMetadataTableDao.findById(formMetadataEntity.getTableid()).orElse(null);
                        tmpmap.put("metatableshow",metadataTableEntity==null?"":metadataTableEntity.getName());
                    }

                    mapList.add(tmpmap);
                }
        );
        return Result.ok(mapList) ;

    }


    @RequestMapping(value = "/getSysFormListTemplateByFormId")
    @ResponseBody
    public  List<Map<String,Object>> getSysFormListTemplateByFormId(String formId) {

        List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();

        List<DevtFormListtemplateEntity>  tempfieldlist = sysCrfFormListTemplateService.getFormListtemplateByFormId(formId);
        tempfieldlist.stream().filter(
                sysCrfFormListtemplateEntity -> {
                    return sysCrfFormListtemplateEntity.getStatus()==1;
                }
        ).forEach(
                (sysCrfFormTemplateEntity) -> {
                    Map<String, Object> tmpmap = (Map<String, Object>) JSON.parseObject(JSON.toJSONString(sysCrfFormTemplateEntity));
                    tmpmap.put("id",sysCrfFormTemplateEntity.getId());
                    tmpmap.put("name",sysCrfFormTemplateEntity.getName());
                    tmpmap.put("active",sysCrfFormTemplateEntity.getActive()!=null&&sysCrfFormTemplateEntity.getActive()==1?"是":"");
                    tmpmap.put("standard",sysCrfFormTemplateEntity.getStandard()!=null&&sysCrfFormTemplateEntity.getStandard()==1?"是":"");
                    tmpmap.put("status",sysCrfFormTemplateEntity.getStatus()!=null&&sysCrfFormTemplateEntity.getStatus()==0?"是":"否");
                    tmpmap.put("style","风格"+sysCrfFormTemplateEntity.getStytle());
                    String pageflag="不分页";
                    pageflag=sysCrfFormTemplateEntity.getPageflag()==2?"前台分页":pageflag;
                    pageflag=sysCrfFormTemplateEntity.getPageflag()==3?"后台分页":pageflag;
                    tmpmap.put("pageflag",pageflag);
                    tmpmap.put("createTime", DateUtil.formatFromDate(DateUtil.FORMATER_YYYY_MM_DD_HH_MM_SS, sysCrfFormTemplateEntity.getCreateTime()));
                    mapList.add(tmpmap);
                }
        );
        return mapList;

    }


    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(DevtFormListtemplateEntity sysCrfFormTemplateEntity, HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> params) throws Exception {

        if (StringUtil.isNullOrSpace(sysCrfFormTemplateEntity.getId())) {
            sysCrfFormTemplateEntity.setId(UUID.randomUUID().toString());
        }else {
            DevtFormListtemplateEntity entity = sysCrfFormListTemplateService.getTemplateById(sysCrfFormTemplateEntity.getId());
            sysCrfFormTemplateEntity.setTemlplesql(entity.getTemlplesql());
        }
        StringBuilder thconf= new StringBuilder();
        thconf.append(params.getOrDefault("searchBtnCfg","0"));
        thconf.append(params.getOrDefault("addBtnCfg","0"));
        sysCrfFormTemplateEntity.setThconf(thconf.toString());

        StringBuilder thcolconf= new StringBuilder();
        thcolconf.append(params.getOrDefault("editBtnCfg","0"));
        thcolconf.append(params.getOrDefault("delBtnCfg","0"));
        sysCrfFormTemplateEntity.setThcolconf(thcolconf.toString());
        sysCrfFormTemplateEntity.setImportconf(params.get("importBtnCfg").toString());

        //详情模版配置
        String temlpleConfigDetail=request.getParameter("temlpleConfigDetail");
        if(!StringUtil.isEmptyOrLength0(temlpleConfigDetail)){
            List<HashMap> temlpleConfigDetailList=(List<HashMap>)JSON.parseArray(temlpleConfigDetail, HashMap.class);
            for (int i = 0; i < temlpleConfigDetailList.size(); i++) {
                HashMap hashMap = temlpleConfigDetailList.get(i);
                DevtFormListtemplConfigEntity sysCrfFormListtemplConfigEntity=StringUtil.mapToObject(DevtFormListtemplConfigEntity.class,hashMap);
                String toString1 = request.getParameter("temlpletype_" + sysCrfFormListtemplConfigEntity.getFormid()).toString();
                sysCrfFormListtemplConfigEntity.setTemlpletype(Integer.parseInt(toString1));
                String toString = request.getParameter("isshow_" + sysCrfFormListtemplConfigEntity.getFormid());
                sysCrfFormListtemplConfigEntity.setIshow(Integer.parseInt(StringUtil.isEmptyOrLength0(toString)?"0":toString));
                if(StringUtil.isEmptyOrLength0(sysCrfFormListtemplConfigEntity.getId())){
                    sysCrfFormListtemplConfigEntity.setId(UUID.randomUUID().toString());
                }
                sysCrfFormListtemplConfigEntity.setTempleid(sysCrfFormTemplateEntity.getId());
//                sysCrfFormListtemplConfigDao.save(sysCrfFormListtemplConfigEntity.getId(),sysCrfFormListtemplConfigEntity);
                sysCrfFormListtemplConfigDao.save(sysCrfFormListtemplConfigEntity);
            }
        }

        sysCrfFormTemplateEntity.setCreateTime(new Timestamp(new Date().getTime()));
        if (sysCrfFormTemplateEntity.getActive() == null) {
            sysCrfFormTemplateEntity.setActive(0);
        }
    
        String metatablesel = request.getParameter("metatablesel");
        List<DevtFormMetadataEntity> metadataEntityList = sysCrfFormMetadataDao.getDataByTempleid(sysCrfFormTemplateEntity.getId());
        for (int i = 0; i < metadataEntityList.size(); i++) {
            DevtFormMetadataEntity sysFormMetadataEntity = metadataEntityList.get(i);
            commonApiDao.deleteObj(sysFormMetadataEntity);
        }
        DevtFormMetadataEntity sysFormMetadataEntity=new DevtFormMetadataEntity();
        sysFormMetadataEntity.setId(UUID.randomUUID().toString());
        sysFormMetadataEntity.setTempleid(sysCrfFormTemplateEntity.getId());
        sysFormMetadataEntity.setTableid(metatablesel);
        sysCrfFormMetadataDao.save(sysFormMetadataEntity);
    
        try {
            //先创建模板
            sysCrfFormTemplateEntity.setStatus(1);
            sysCrfFormListTemplateService.save(sysCrfFormTemplateEntity);
            
            return  Result.ok();
        } catch (Exception ex) {

            logger.error("【执行" + this.getClass().getName() + ".save() 方法失败 】异常：" + ex.getMessage());
            return Result.error("操作错误，请稍候再试！");
        }
        
    }

    @RequestMapping(value = "/active")
    @ResponseBody
    public Result active(String id,String formId,
                       HttpServletRequest request, HttpServletResponse response) throws Exception{

        String result = "";
        DevtFormListtemplateEntity sysCrfFormListtemplateEntity=sysCrfFormListTemplateService.getTemplateById(id);
        List<DevtFormListtemplateEntity> sysCrfFormTemplateEntityList = sysCrfFormListTemplateService.getFormListtemplateByFormId(formId);

        for(int i=0;i<sysCrfFormTemplateEntityList.size();i++){
            if(sysCrfFormTemplateEntityList.get(i).getId().equals(id)){
                sysCrfFormTemplateEntityList.get(i).setActive(1);
            }
        }

        try {
            sysCrfFormListTemplateService.saveEntityList(sysCrfFormTemplateEntityList);

            return Result.ok();
        }
        catch (Exception ex){
            logger.error("【执行" + this.getClass().getName() + ".active() 方法失败 】异常：" + ex.getMessage());
            return Result.error("操作错误，请稍候再试！");
        }

    }


    @RequestMapping(value = "/saveClone")
    @ResponseBody
    public Result saveClone(String id, String name,String templateId ,HttpServletRequest request, HttpServletResponse response) throws Exception{

        String result ;
        try{
            DevtFormListtemplateEntity sysCrfFormTemplateEntity = sysCrfFormListTemplateService.getTemplateById(templateId);
            
            //创建克隆模板
            DevtFormListtemplateEntity sysCrfFormTemplate = new DevtFormListtemplateEntity();
            BeanUtils.copyProperties(sysCrfFormTemplateEntity,sysCrfFormTemplate);

            sysCrfFormTemplate.setId(UUID.randomUUID().toString());
            sysCrfFormTemplate.setName(name);
            sysCrfFormTemplate.setCreateTime(new Timestamp(new Date().getTime()));
            Integer maxxh = sysCrfFormListTemplateService.getMaxXh(sysCrfFormTemplateEntity.getFlid());
            maxxh=maxxh==null?1:(maxxh+1);
            sysCrfFormTemplate.setXh(maxxh);
            
            sysCrfFormListTemplateService.save(sysCrfFormTemplate);
            result = "{\"success\":true,\"msg\":\"克隆成功！\"}";
            return  Result.ok();
        } catch (Exception ex) {

            logger.error("【执行" + this.getClass().getName() + ".saveClone() 方法失败 】异常：" + ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试！");
        }

    }


    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result deltemplet(String id,HttpServletRequest request,
                           HttpServletResponse response)throws Exception{
        String result;
        try {
            DevtFormListtemplateEntity sysCrfFormTemplateEntity = sysCrfFormListTemplateService.getTemplateById(id);
            sysCrfFormTemplateEntity.setStatus(0);
            sysCrfFormListTemplateService.save(sysCrfFormTemplateEntity);

            return Result.ok();
        }
        catch (Exception ex){

            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage());
            return Result.error("系统错误，请稍候再试！");
        }


    }

    @RequestMapping(value = "/export")
    public void export(@RequestParam Map<String, String> paramMap, HttpServletResponse response) throws Exception {

        String formidlist = paramMap.get("formidlist");
        if(!StringUtil.isEmptyOrLength0(formidlist)&&formidlist.endsWith(",")){
            formidlist=formidlist.substring(0,formidlist.length()-1);
        }
        String[] split = formidlist.split(",");

        TableConfig tableConfig=new TableConfig("devt_form_listtemplate",
                "表单基础配置表","id","",Boolean.TRUE);
        tableConfig.setSubtableList(new ArrayList<>());
        tableConfig.getSubtableList().add(new TableConfig("devt_form_listtempl_args",
                "表单列表查询参数配置表","templeid","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_form_listtempl_theader",
                "表单列表表头配置表","templeid","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_form_listtempl_otherbtn",
                "表单列表其它按钮配置表","templeid","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_form_design",
                "表单编辑表单配置表","templateid","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_form_fieldconfig",
                "表单编辑表单字段配置表","templateid","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_form_metadata",
                "表单关联元数据配置表","templeid","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_form_fieldcheck",
                "表单列表查询参数校验配置表","templeid","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_form_type",
                "表单列表查询参数校验配置表","id","flid",Boolean.TRUE));


        List<TableConfig> tableConfigList=new ArrayList();
        tableConfigList.add(tableConfig);
        HashMap<String,List<Object>> dataMap=new HashMap<>();
        dataMap.put(tableConfig.getTablename(),new ArrayList<>());
        dataMap.get(tableConfig.getTablename()).addAll(Arrays.asList(split));

        DataExportUtil dataExportUtil = DataExportUtil.createDataExportUtil(jdbcTemplate.getDataSource(), true);
        String sqlContent=dataExportUtil.exportData(tableConfigList,dataMap,new ArrayList<>());
        String  contentType="text/sql";
        response.setContentType(StringUtil.isEmptyOrLength0(contentType)?"application/octet-stream":contentType);
        String formid = formidlist.replaceAll(",", "_");
        formid=formid.indexOf("_")>0?formid.substring(0,formid.indexOf(",")):formid;
        response.addHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode("表单配置导出_"+formid +".sql","UTF-8"));
        response.setCharacterEncoding("utf-8");
        InputStream inputStream=new ByteArrayInputStream(sqlContent.getBytes(StandardCharsets.UTF_8));
        byte[] byteData=new byte[1024*1024*3];
        int count=-1;
        ServletOutputStream servletOutputStream= response.getOutputStream();
        while ((count=inputStream.read(byteData))!=-1){
            servletOutputStream.write(byteData,0,count);
        }
        servletOutputStream.flush();
    }
}
